// pages//chat/chat.js 
var app = getApp();
var heartCheck = {
  timeout: 1000000,
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function () {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  start: function () {
    this.timeoutObj = setTimeout(() => {
      console.log("发送ping");
      wx.sendSocketMessage({
        data: "ping",
        success() {
          console.log("发送ping成功");
        }
      });
      this.serverTimeoutObj = setTimeout(() => {
        wx.closeSocket();
      }, this.timeout);
    }, this.timeout);
  }
};
Page({

  /**
   * 页面的初始数据
   */
  ipt_text: '',
  data: {
    news: [
      // 消息模板分类：
      // template:0   第一次进入消息页时展示的欢迎语
      // template:1   由产品页进入时发送的产品信息
      // template:2   发送的文字消息
      // send:0       我发送的
      // send:1       别人发送的
      {
        date: '2018-10-22',
        list: [
          {
            time: '14:25',
            template: 1,
            send: 0,
            userImg: 'http://www.meiliancheng.cn/public/meiliancheng/imagezy/hgj/banner.png',
            productImg: 'http://www.meiliancheng.cn/public/meiliancheng/imagezy/hgj/banner.png',
            text: '产品名称产品名称',
          },
        ],
      },
      {
        date: '2018-10-28',
        list: [
          {
            time: '14:25',
            template: 2,
            send: 1,
            userImg: 'http://www.meiliancheng.cn/public/meiliancheng/imagezy/hgj/banner.png',
            text: '消息内容，消息内容',
          },
          {
            time: '14:25',
            template: 2,
            send: 0,
            userImg: 'http://www.meiliancheng.cn/public/meiliancheng/imagezy/hgj/banner.png',
            text: '消息内容，消息内容',
          },
        ]
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var cid = options.cid;
    app.siteInfo.cid = cid;
    that.setData({
      cid: app.siteInfo.cid
    })
    console.log(cid);
    var islink = app.siteInfo.islink;
    if (!islink) {
      that.linkSocket();
      app.siteInfo.islink = true
    }
    wx.showLoading({
      title: '加载中',
      icon: 'loading'
    })

    if (app.siteInfo.user.logo.indexOf('https') != -1) {
      var logoimg = app.siteInfo.user.logo
    } else {
      var logoimg = app.siteInfo.imgpath + app.siteInfo.user.logo
    }
    wx.request({
      url: app.siteInfo.managerpath + 'chat',
      method: "post",
      data: {
        cid: cid,
        mid: app.siteInfo.mid,
        pid: app.siteInfo.pid
      },
      success: function (res) {
        wx.hideLoading()
        that.setData({
          phone: res.data.phone,
          m_userimg: res.data.mlogo,
          chat_list: res.data.chat_list,
          customerlogo: res.data.logo
        })
        that.scrollTop();
      }
    })
  },
  linkSocket: function () {
    var that = this;

    // wx.connectSocket({
    //   url: 'wss://',
    //   success() {
    //     console.log('连接成功')
    //     that.initEventHandle();
    //   }

    // });
  },
  initEventHandle: function () {
    let that = this
    wx.onSocketMessage((res) => {
      //收到消息
      var o = JSON.parse(res.data);
      console.log(res)
      if (o.sid == app.siteInfo.cid && o.type == 'say' && o.rid == parseInt(app.siteInfo.pid) && o.pid == parseInt(app.siteInfo.pid)) {
        console.log('yes')
        that.reserveMsg(o);
      }
      heartCheck.reset().start()
    })
    wx.onSocketOpen(() => {
      console.log('WebSocket连接打开')
      // wx.hideLoading()

      heartCheck.reset().start()
    })
    wx.onSocketError((res) => {
      console.log('WebSocket连接打开失败')
      app.siteInfo.islink = false
      that.reconnect()
    })
    wx.onSocketClose((res) => {
      that.reconnect();
      // wx.showLoading({
      //   title: '',
      //   icon:"loading"
      // })
      app.siteInfo.islink = false
      console.log('WebSocket 已关闭！')

    })
  },
  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    if (this.data.limit < 1200) {
      this.timer = setTimeout(() => {
        this.linkSocket();
        this.lockReconnect = false;
      }, 5000);
      this.setData({
        limit: this.data.limit + 1
      })
    } else {
      this.timer = setTimeout(() => {
        this.linkSocket();
        this.lockReconnect = false;
      }, 5000);
      this.setData({
        limit: 1
      })
    }
  },
  reserveMsg: function (n) {
    var that = this;
    var chat_lists = that.data.chat_list;
    var t = {
      uid: app.siteInfo.uid,
      pid: app.siteInfo.pid,
      content: n.content,
      headimg: that.data.customerlogo,
      flag: 1
    };
    chat_lists.push(t);
    that.setData({
      chat_list: chat_lists,
      ipt_text: '',
      name111: 1
    }, function (res) {
      // console.log('回调打印')
      // console.log(that.data.chat_list);
    })
    // console.log(that.data.chat_list);
    // console.log(chat_lists);
    console.log('收到')
    that.scrollTop();
  },
  scrollTop: function () {
    var that = this;
    var chat_list = that.data.chat_list;
    if (chat_list) {
      var chat_listLen = chat_list.length;
    } else {
      var chat_listLen = 1;
    }

    var scrolltop = chat_listLen * 300;
    that.setData({
      scrolltop: scrolltop,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.request({
      url: app.siteInfo.chatroot + "clearMsg",
      data: { 'sid': app.siteInfo.cid, 'rid': that.data.pid },
      method: 'post',
      success: function (data) {
      }
    })
    this.scrollTop();
  },
  clearInput: function () {
    this.setData({
      ipt_text: ""
    })
  },
  msginput: function (e) {
    this.setData({
      ipt_text: e.detail.value
    })
  },
  sendmsg: function (e) {
    var formid = e.detail.formId;
    var that = this;
    var a = this.data.ipt_text
    var chat_list = this.data.chat_list
    if (null == a || null == a || "" == a) return wx.showToast({
      title: "内容不能为空",
      icon: "none"
    }), !1;
    var t = {
      uid: app.siteInfo.uid,
      pid: app.siteInfo.pid,
      content: a,
      headimg: that.data.m_userimg,
      flag: 2
    }
    chat_list.push(t)
    that.setData({
      chat_list: chat_list,
      ipt_text: '',
    })
    that.scrollTop();
    wx.request({
      url: app.siteInfo.managerpath + "send_msg",
      data: {
        uid: app.siteInfo.cid,
        pid: app.siteInfo.pid,
        mid: app.siteInfo.mid,
        rid: app.siteInfo.cid,
        sid: app.siteInfo.pid,
        log_type: 1,
        is_new: 1,
        flag: 2,
        content: a,
        formid: formid
      },
      method: "post",
      success: function (res) {
        // console.log(res)
      },
      error: function (res) {
        wx.showModal({
          content: res,
          showCancel: !1
        });
      }
    });
    var abc = { 'pid': parseInt(app.siteInfo.pid), 'uid': parseInt(app.siteInfo.cid), 'type': "say", 'rid': parseInt(app.siteInfo.cid), 'sid': parseInt(app.siteInfo.pid), 'content': a, 'log_type': 0 };
    abc = JSON.stringify(abc);
    wx.sendSocketMessage({
      data: abc,
      success: function (res) {
        // that.saveMsg(a);
        heartCheck.reset().start()
      }
    });



  },
  saveMsg: function (a) {
    wx.request({
      url: app.siteInfo.chatroot + "saveMsg",
      data: a,
      method: 'post',
      success: function (data) {
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})